package com.assic.utils.web.tag;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
 * @author Kerbores<br>
 *         ForeachTag.java Create at 2014年2月11日
 * 
 */
public class ForeachTag extends SimpleTagSupport {
	private Object items;
	private String var;

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.jsp.tagext.SimpleTagSupport#doTag()
	 */
	@Override
	public void doTag() throws JspException, IOException {
		Iterator ite = null;
		Object tempItem = items;
		// 如果是集合
		if (tempItem instanceof Collection) {
			ite = ((Collection) tempItem).iterator();
		}
		// 如果是数组
		else if (tempItem instanceof Object[]) {
			ite = Arrays.asList((Object[]) tempItem).iterator();
		} else {
			throw new RuntimeException("不能转换");
		}
		// 进行迭代
		while (ite.hasNext()) {
			Object obj = ite.next();
			getJspContext().setAttribute(var, obj);
			// 输出标签体
			getJspBody().invoke(null);
		}
	}

	/**
	 * @return the items
	 */
	public Object getItems() {
		return items;
	}

	/**
	 * @param items
	 *            the items to set
	 */
	public void setItems(Object items) {
		this.items = items;
	}

	/**
	 * @return the var
	 */
	public String getVar() {
		return var;
	}

	/**
	 * @param var
	 *            the var to set
	 */
	public void setVar(String var) {
		this.var = var;
	}

}
